package cn.akwangl.common.uoload.aliyun;

import cn.akwangl.common.uoload.aliyun.properties.RAMProperties;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author: youyongkun
 * @Date: 2019/9/11 13:42
 * 功能描述:
 * 阿里云 RAM 角色管理
 */
@Component
public class ALiRAM {

    // log日志

    public final String product = "Sts";

    @Autowired
    private RAMProperties ramProperties;

    /**
     * @author: youyongkun
     * @Date: 2019/9/11 15:13
     * 功能描述:
     * 获取临时访问权限的 toKen 默认有效期15分钟,返回 AssumeRoleResponse 对象
     * <p>
     * Expiration: response.getCredentials().getExpiration()
     * Access Key Id: response.getCredentials().getAccessKeyId()
     * Access Key Secret: response.getCredentials().getAccessKeySecret()
     * Security Token: response.getCredentials().getSecurityToken()
     * RequestId: response.getRequestId()
     */
    public AssumeRoleResponse getToken() {
        try {
            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
            DefaultProfile.addEndpoint("", this.product, ramProperties.getEndpoint());
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", ramProperties.getAccessKeyId(), ramProperties.getAccessKeySecret());
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(ramProperties.getRoleArn());
            request.setRoleSessionName(ramProperties.getRoleSessionName());
            request.setPolicy(ramProperties.getPolicy()); // 若policy为空，则用户将获得该角色下所有权限
            request.setDurationSeconds(ramProperties.getDurationSeconds()); // 设置凭证有效时间
            return client.getAcsResponse(request);
        } catch (ClientException e) {
            System.out.println("Failed：");
            System.out.println("Error code: " + e.getErrCode());
            System.out.println("Error message: " + e.getErrMsg());
            System.out.println("RequestId: " + e.getRequestId());
            return null;
        }
    }
}
